package com.qs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.mapper.RoleMapper;
import com.qs.mapper.UserMapper;
import com.qs.mapper.entity.Form;
import com.qs.mapper.entity.Role;
import com.qs.mapper.entity.User;
import com.qs.service.UserService;
import com.qs.service.bo.RoleBO;
import com.qs.service.bo.UserBO;
import com.qs.util.BeanCopyUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final RoleMapper roleMapper;

    @Override
    public String add(UserBO userBO) {
        User user = BeanCopyUtils.copyBean(userBO, User.class);
        isExist(User::getUsername, user.getUsername());
        boolean saved = save(user);
        return saved ? "新增成功" : "新增失败";
    }

    @Override
    public String edit(UserBO userBO) {
        // 清除该用户在用户角色记录表中的所有数据
        Integer i = baseMapper.deleteUserRole(userBO.getId());
        // 插入新的记录
        if (!userBO.getRoleList().isEmpty()) {
            Integer j = baseMapper.insertUserRole(userBO.getId(), userBO.getRoleList());
        }
        // 更新用户信息
        User user = BeanCopyUtils.copyBean(userBO, User.class);
        boolean updated = updateById(user);
        return updated ? "修改成功" : "修改失败";
    }

    @Override
    public Page<UserBO> queryByPage(String username, Page<User> page) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.like(StringUtils.hasText(username), User::getUsername, username);
        page(page, lambdaQueryWrapper);
        List<User> records = page.getRecords();
        List<UserBO> userBOList = BeanCopyUtils.copyBeanList(records, UserBO.class);
        for (UserBO userBO : userBOList) {
            List<Long> roleList = roleMapper.getRoleListByUsername(userBO.getUsername()).stream().map(Role::getId).collect(Collectors.toList());
            userBO.setRoleList(roleList);
        }
        Page<UserBO> result = new Page<>();
        result.setTotal(page.getTotal());
        result.setRecords(userBOList);
        return result;
    }

    private void isExist(SFunction<User, ?> column, Object value) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(column, value);
        User user = getOne(queryWrapper);
        if (Objects.nonNull(user)) {
            throw new RuntimeException("用户已存在");
        }
    }
}
